package com.sinosoft.sm.message.service;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sinosoft.sm.message.SDUtils.SDUtils;
import com.sinosoft.sm.message.entity.MessageRecordEntity;
import com.sinosoft.sm.message.manager.api.RecordManager;
import com.sinosoft.sm.message.service.api.RecordService;
import com.sinosoft.sm.message.web.dto.RecordData;
import com.sinosoft.sm.system.common.SystemContants;
import com.sinosoft.sm.system.common.entity.PaginationEntity;
import com.sinosoft.sm.system.common.exception.BusinessException;
import com.sinosoft.sm.system.common.utils.StringUtil;
import com.sinosoft.sm.system.security.SecurityUtil;
import com.sinosoft.sm.user.entity.UserEntity;

/**
 * 信息记录服务实现
 * @author leichao
 *
 */
public class RecordServiceImpl implements RecordService{

	RecordManager recordManager;
	
	public void setRecordManager(RecordManager recordManager) {
		this.recordManager = recordManager;
	}

	/**
	 * 根据条件查询信息记录
	 */
	public PaginationEntity getRecord(RecordData recordData, int page, int rows) {
		PageHelper.startPage(page, rows);
		recordData.setUsername(SecurityUtil.getUsername());
		List<UserEntity> users = recordManager.getRecords(recordData);
		@SuppressWarnings({ "rawtypes", "unchecked" })
		PageInfo pageInfo = new PageInfo(users);
		return new PaginationEntity((int)pageInfo.getTotal(), pageInfo.getPageNum(), users);
	}

	/**
	 * 1.发送短信，捕获发送短信的结果，有问题则抛出异常
	 * 2.添加消息记录
	 */
	public boolean addMessageRecord(MessageRecordEntity messageRecordEntity) {
		if(StringUtil.isBlank(messageRecordEntity.getReceiver())||
		   StringUtil.isBlank(messageRecordEntity.getMessage())){
			return false;
		}
		String phones = messageRecordEntity.getReceiver().trim();
		boolean verification = vertifyPhones(phones);
		if(!verification){
			throw new BusinessException("手机号格式错误或未使用英文逗号");
		}else{
			//若只是单个手机号，则需要在其结尾加一个逗号
			if(phones.split(",").length == 1){
				phones = phones+",";
			}
		}
		String errorMessage = SDUtils.sendMessage(phones, messageRecordEntity.getMessage());
		if(!StringUtil.isBlank(errorMessage)){
			messageRecordEntity.setState(SystemContants.SEND_MESSAGE_FAILURE);
			messageRecordEntity.setExplain(errorMessage);
			messageRecordEntity.setId(UUID.randomUUID().toString());
			messageRecordEntity.setUsername(SecurityUtil.getUsername());
			messageRecordEntity.setSendtime(new Date());
			recordManager.addMessageRecord(messageRecordEntity);
			return false;
		}else{
			messageRecordEntity.setState(SystemContants.SEND_MESSAGE_SUCCESS);
		}
		messageRecordEntity.setId(UUID.randomUUID().toString());
		messageRecordEntity.setUsername(SecurityUtil.getUsername());
		messageRecordEntity.setSendtime(new Date());
		recordManager.addMessageRecord(messageRecordEntity);
		return true;
	}
	
	/**
	 * 验证手机号及英文逗号
	 * 有一个验证错误则返回false
	 * @param phones 手机号
	 * @return false/true
	 */
	private boolean vertifyPhones(String phones){
		String[] phoneArr = phones.split(",");
		Boolean rs = null;
		for(int i=0;i<phoneArr.length;i++){
			String regEx = "1[34578]\\d{9}";
		    // 编译正则表达式
		    Pattern pattern = Pattern.compile(regEx);
		    // 忽略大小写的写法
		    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
		    Matcher matcher = pattern.matcher(phoneArr[i]);
		    // 字符串是否与正则表达式相匹配
		    rs = matcher.matches();
		    if(!rs){
		    	break;
		    }
		}
		return rs;
	}
}
